<template>
  <div class="app-container">
    <!-- 统计概览卡片 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon article">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-number">{{ overviewData.totalArticles || 0 }}</div>
              <div class="stats-label">文章总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon read">
              <el-icon><View /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-number">{{ overviewData.totalReads || 0 }}</div>
              <div class="stats-label">总阅读量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon like">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-number">{{ overviewData.totalLikes || 0 }}</div>
              <div class="stats-label">总点赞数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon comment">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-number">{{ overviewData.totalComments || 0 }}</div>
              <div class="stats-label">总评论数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <!-- 阅读趋势图 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>阅读趋势</span>
              <el-date-picker
                v-model="trendDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                @change="getTrendData"
                size="small"
              />
            </div>
          </template>
          <div ref="trendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>

      <!-- 分类统计饼图 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>分类统计</span>
          </template>
          <div ref="categoryChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt20">
      <!-- 热门文章排行 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>热门文章排行</span>
              <el-select v-model="popularType" @change="getPopularData" size="small">
                <el-option label="按阅读量" value="read" />
                <el-option label="按点赞数" value="like" />
                <el-option label="按收藏数" value="favorite" />
              </el-select>
            </div>
          </template>
          <div class="popular-list">
            <div 
              v-for="(item, index) in popularList" 
              :key="item.id" 
              class="popular-item"
            >
              <div class="rank" :class="'rank-' + (index + 1)">{{ index + 1 }}</div>
              <div class="content">
                <div class="title">{{ item.title }}</div>
                <div class="stats">
                  <span>阅读: {{ item.readCount }}</span>
                  <span>点赞: {{ item.likeCount }}</span>
                  <span>收藏: {{ item.favoriteCount }}</span>
                </div>
              </div>
              <div class="value">{{ getPopularValue(item) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 用户活跃度 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>用户活跃度</span>
              <el-select v-model="activityPeriod" @change="getActivityData" size="small">
                <el-option label="最近7天" value="7" />
                <el-option label="最近30天" value="30" />
                <el-option label="最近90天" value="90" />
              </el-select>
            </div>
          </template>
          <div ref="activityChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 评论统计表格 -->
    <el-row class="mt20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>评论统计</span>
          </template>
          <el-table :data="commentStats" style="width: 100%">
            <el-table-column prop="techniqueTitle" label="文章标题" :show-overflow-tooltip="true" />
            <el-table-column prop="commentCount" label="评论数" width="100" align="center" />
            <el-table-column prop="avgRating" label="平均评分" width="100" align="center">
              <template #default="scope">
                <el-rate v-model="scope.row.avgRating" disabled show-score text-color="#ff9900" />
              </template>
            </el-table-column>
            <el-table-column prop="lastCommentTime" label="最新评论时间" width="180" align="center">
              <template #default="scope">
                <span>{{ parseTime(scope.row.lastCommentTime, '{y}-{m}-{d} {h}:{i}') }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="category" label="分类" width="100" align="center" />
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button link type="primary" @click="viewComments(scope.row)">查看评论</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Stats">
import { getStatsOverview, getReadTrend, getCategoryStats, getPopularArticles, getUserActivityStats, getCommentStats } from "@/api/fishing/stats";
import { Document, View, Star, ChatDotRound } from '@element-plus/icons-vue';
import * as echarts from 'echarts';

const { proxy } = getCurrentInstance();

const overviewData = ref({});
const trendDateRange = ref([]);
const popularType = ref('read');
const activityPeriod = ref('7');
const popularList = ref([]);
const commentStats = ref([]);

const trendChart = ref(null);
const categoryChart = ref(null);
const activityChart = ref(null);

let trendChartInstance = null;
let categoryChartInstance = null;
let activityChartInstance = null;

/** 获取统计概览数据 */
function getOverviewData() {
  getStatsOverview().then(response => {
    overviewData.value = response.data;
  });
}

/** 获取阅读趋势数据 */
function getTrendData() {
  const params = {};
  if (trendDateRange.value && trendDateRange.value.length === 2) {
    params.startDate = trendDateRange.value[0];
    params.endDate = trendDateRange.value[1];
  }
  
  getReadTrend(params).then(response => {
    const data = response.data;
    const option = {
      title: {
        text: '阅读趋势',
        left: 'center',
        textStyle: {
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: data.dates || []
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        name: '阅读量',
        type: 'line',
        data: data.reads || [],
        smooth: true,
        itemStyle: {
          color: '#409EFF'
        }
      }]
    };
    
    if (trendChartInstance) {
      trendChartInstance.setOption(option);
    }
  });
}

/** 获取分类统计数据 */
function getCategoryData() {
  getCategoryStats().then(response => {
    const data = response.data;
    const option = {
      title: {
        text: '分类统计',
        left: 'center',
        textStyle: {
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      series: [{
        name: '文章数量',
        type: 'pie',
        radius: '60%',
        data: data || [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    };
    
    if (categoryChartInstance) {
      categoryChartInstance.setOption(option);
    }
  });
}

/** 获取热门文章数据 */
function getPopularData() {
  getPopularArticles({ type: popularType.value, limit: 10 }).then(response => {
    popularList.value = response.data || [];
  });
}

/** 获取用户活跃度数据 */
function getActivityData() {
  getUserActivityStats({ period: activityPeriod.value }).then(response => {
    const data = response.data;
    const option = {
      title: {
        text: '用户活跃度',
        left: 'center',
        textStyle: {
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['评论数', '点赞数', '收藏数'],
        bottom: 0
      },
      xAxis: {
        type: 'category',
        data: data.dates || []
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '评论数',
          type: 'bar',
          data: data.comments || [],
          itemStyle: { color: '#67C23A' }
        },
        {
          name: '点赞数',
          type: 'bar',
          data: data.likes || [],
          itemStyle: { color: '#E6A23C' }
        },
        {
          name: '收藏数',
          type: 'bar',
          data: data.favorites || [],
          itemStyle: { color: '#F56C6C' }
        }
      ]
    };
    
    if (activityChartInstance) {
      activityChartInstance.setOption(option);
    }
  });
}

/** 获取评论统计数据 */
function getCommentData() {
  getCommentStats().then(response => {
    commentStats.value = response.data || [];
  });
}

/** 获取热门文章对应的数值 */
function getPopularValue(item) {
  switch(popularType.value) {
    case 'read': return item.readCount;
    case 'like': return item.likeCount;
    case 'favorite': return item.favoriteCount;
    default: return item.readCount;
  }
}

/** 查看评论 */
function viewComments(row) {
  proxy.$router.push({
    path: '/fishing-technique/comment',
    query: { techniqueId: row.techniqueId }
  });
}

/** 初始化图表 */
function initCharts() {
  nextTick(() => {
    // 初始化趋势图表
    if (trendChart.value) {
      trendChartInstance = echarts.init(trendChart.value);
    }
    
    // 初始化分类图表
    if (categoryChart.value) {
      categoryChartInstance = echarts.init(categoryChart.value);
    }
    
    // 初始化活跃度图表
    if (activityChart.value) {
      activityChartInstance = echarts.init(activityChart.value);
    }
    
    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      trendChartInstance?.resize();
      categoryChartInstance?.resize();
      activityChartInstance?.resize();
    });
    
    // 加载数据
    getTrendData();
    getCategoryData();
    getActivityData();
  });
}

/** 页面初始化 */
onMounted(() => {
  // 设置默认日期范围为最近30天
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
  trendDateRange.value = [
    start.getFullYear() + '-' + String(start.getMonth() + 1).padStart(2, '0') + '-' + String(start.getDate()).padStart(2, '0'),
    end.getFullYear() + '-' + String(end.getMonth() + 1).padStart(2, '0') + '-' + String(end.getDate()).padStart(2, '0')
  ];
  
  getOverviewData();
  getPopularData();
  getCommentData();
  initCharts();
});

/** 页面销毁时清理图表 */
onUnmounted(() => {
  trendChartInstance?.dispose();
  categoryChartInstance?.dispose();
  activityChartInstance?.dispose();
  window.removeEventListener('resize', () => {});
});
</script>

<style scoped>
.mb20 {
  margin-bottom: 20px;
}

.mt20 {
  margin-top: 20px;
}

.stats-card {
  height: 120px;
}

.stats-item {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stats-icon.article {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.read {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.like {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.comment {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-content {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.popular-list {
  max-height: 300px;
  overflow-y: auto;
}

.popular-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.popular-item:last-child {
  border-bottom: none;
}

.rank {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  margin-right: 15px;
  font-size: 14px;
}

.rank-1 {
  background: #f56c6c;
}

.rank-2 {
  background: #e6a23c;
}

.rank-3 {
  background: #67c23a;
}

.rank:not(.rank-1):not(.rank-2):not(.rank-3) {
  background: #909399;
}

.popular-item .content {
  flex: 1;
}

.popular-item .title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.popular-item .stats {
  font-size: 12px;
  color: #909399;
}

.popular-item .stats span {
  margin-right: 15px;
}

.popular-item .value {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}
</style>